package com.leilei.dao.impl;

import com.leilei.dao.IAddressDao;
import com.leilei.entity.Address;
import com.leilei.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AddressDaoImpl implements IAddressDao {

    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());

    @Override
    public int saveAddress(Address address) {

        String sql = "insert into address(uid, address, tel) values(?, ?, ?)";

        try {
            return queryRunner.update(sql, address.getUid(), address.getAddress(), address.getTel());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public int updateAddress(Address address) {

        String sql = "update address uid = ?, address = ?, tel = ? where did = ?";

        try {
            return queryRunner.update(sql, address.getUid(), address.getAddress(), address.getTel(), address.getDid());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public Address selectAddressByDid(int did) {

        String sql = "select did, uid, address, tel from address where did = ?";

        try {
            return queryRunner.query(sql, new BeanHandler<Address>(Address.class), did);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return null;
    }

    @Override
    public List<Address> selectAllAddress(int uid) {

        String sql = "select did, uid, address, tel from address where uid = ?";

        try {
            return queryRunner.query(sql, new BeanListHandler<Address>(Address.class), uid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return null;
    }
}
